<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Silence
 * Date: 3/8/12
 * Time: 3:51 AM
 * To change this template use File | Settings | File Templates.
 */

require_once('api.php');
require_once('constants.php');

$con = db_prepare();

switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        if (isset($_GET['item']) && ($_GET['item'] === 'read_items')) {
            $raw_data = get_items();
            $data = build_items_tree($raw_data);
            $data = array('text'=> '.', 'children'=> $data);
            print json_encode($data);
        }
        break;
    case 'POST':
        // var_dump($_POST);
        // var_dump($_GET);
        if (isset($_GET['item']) && ($_GET['item'] === 'update_items')) {
            $data = json_decode($HTTP_RAW_POST_DATA);
            /*$sql = "UPDATE `items` SET `cost` = '$data->cost', `budget` = '$data->budget'
                    WHERE `id` = $data->id";
            db_die($result = mysql_query($sql));

            $temp = $data->pid;
            while ($temp != 0) {
                $sql = "SELECT * FROM `items` WHERE `id` = $temp";
                db_die($result = mysql_query($sql));

                while ($row = mysql_fetch_array($result)) {
                    $row['cost'] += $data->cost;
                    $nid = $row['id'];
                    $nitem = $row['item'];
                    $ndescription = $row['description'];
                    $ncost = $row['cost'];
                    $nmaxR = $row['maxR'];
                    $nbudget = $row['budget'];
                    $npid = $row['pid'];

                    $sql = "UPDATE `items` SET `item` = '$nitem', `description` = '$ndescription',
                            `cost` = '$ncost', `maxR` = '$nmaxR', `budget` = '$nbudget', `pid` = '$npid'
                            WHERE `id` = $nid";
                    db_die($result2 = mysql_query($sql));
                    $temp = $row['pid'];
                }
            }*/

            // check if it is an array
            if (is_array($data)) {
                foreach ($data as $item) {
                    $sql = "UPDATE `items` SET `item` = '$item->item', `description` = '$item->description',
                            `cost` = '$item->cost', `maxR` = '$item->maxR', `budget` = '$item->budget',
                            `pid` = '$item->pid' WHERE `id` = $item->id";
                    db_die($result = mysql_query($sql));
                }
            }
            else {
                $item = $data;
                $sql = "UPDATE `items` SET `item` = '$item->item', `description` = '$item->description',
                        `cost` = '$item->cost', `maxR` = '$item->maxR', `budget` = '$item->budget',
                        `pid` = '$item->pid' WHERE `id` = $item->id";
                db_die($result = mysql_query($sql));
            }
        }
        break;
    default:
        break;
}


mysql_close($con);